package cs.xwi7xwa.activities;

import java.io.IOException;

import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import cs.xwi7xwa.R;
import cs.xwi7xwa.data.ExhibitDbAdapter;
import cs.xwi7xwa.templates.BumpListTemplate;

public class ExhibitListView extends BumpListTemplate {
    private ExhibitDbAdapter dbAdapter;
    private Cursor cursor;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);

	// Load the database
	dbAdapter = new ExhibitDbAdapter(this);
	
	try {
	    dbAdapter.open();
	} catch (IOException e) {
	    e.printStackTrace();
	}

	// Populate the page with the exhibits from the database
	refreshList();

	// This list should be filterable
	getListView().setTextFilterEnabled(true);
	
    // Log this method's execution
    log(null);
    }

    /**
     * Fetch exhibits from the database and list them out in this Activity
     */
    private void refreshList() {
	// Fetch all exhibits from the database
	cursor = dbAdapter.fetchAll();
	startManagingCursor(cursor);

	// Displaying only the name column
	String[] displayCol = new String[] { ExhibitDbAdapter.KEY_NAME };

	// The list goes to here
	int[] toView = new int[] { R.id.list_item };

	// Wrap items from cursor in layout list_item, display only the data
	// from displayCol columns, and send it over to the toView view in this
	// Activity
	setListAdapter(new SimpleCursorAdapter(this, R.layout.list_item,
		cursor, displayCol, toView));
	
	// Log this method's execution
    log(null);
    }

    @Override
    protected void onListItemClick(ListView listView, View view, int position,
	    long id) {
	super.onListItemClick(listView, view, position, id);

	// Load the clicked item from the database
	Cursor c = cursor;
	c.moveToPosition(position);

	// Pass id, name, description, and image path of this item to
    // ExhibitView
    Intent intent = new Intent(this, ExhibitView.class);
    intent.putExtra(ExhibitDbAdapter.KEY_ID, (int) id);
    String name = c.getString(c.getColumnIndexOrThrow(ExhibitDbAdapter.KEY_NAME));
    intent.putExtra(ExhibitDbAdapter.KEY_NAME, name);
    intent.putExtra(ExhibitDbAdapter.KEY_DESC, c.getString(c
            .getColumnIndexOrThrow(ExhibitDbAdapter.KEY_DESC)));
    intent.putExtra(ExhibitDbAdapter.KEY_IMAGE, c.getString(c
            .getColumnIndexOrThrow(ExhibitDbAdapter.KEY_IMAGE)));

    startActivityForResult(intent, 0);
    
    // Log this method's execution
    log(new String[]{"ID: " + id, "Name: " + name});
    }
}
